/**
 * Created by Luoqb on 2017/5/2.
 */
define([
    "dojo",
    "modules/common/tools/util",
    "modules/common/tools/datastore",
    "modules/common/tools/moment"
], function (dojo, util,datastore,moment) {
    var validate = null;
    var timer = null;
    var index = 0;
    var module = {
        initPage: function () {
            validate = module.validateForm();
            //办理新卡
            $("#newCard").bind("click",function () {
                u2ds.loadMainHtml("test", {}, function () {

                })
            });
            //充值
            $("#recharge").bind("click",function () {
                module.initRecharge();
            });
            $("#type").bind("change",function () {
                var typeId = $(this).val();
                var data = util.getTokenData();
                dojo.mixin(data, {id: typeId});
                util.post("memberCard/queryById", data).then(function (d) {
                    if (d.code == 200) {
                        $("#number").val(d.data.maxNumber);
                        $("#carPrice").val(d.data.titleAccount);
                        $("#priceNew").val(d.data.price);
                    }
                });
            });

            $("#fixOrder").bind("click",function () {
                module.fixOrder("#tbody","#date");
            });
            $("#fixOrder5F").bind("click",function () {
                module.fixOrder("#tbody5F","#date5F");
            });

            //退订4F
            $("#tuiding4F").bind("click",function(){
                $(".tdContent").each(function(){
                    var bgcolor = $(this).css("background-color");
                    if(bgcolor=='rgb(0, 128, 0)'){
                        var orderId = $(this).attr("order-id");
                        var type = $(this).attr("data-type");
                        if(type==undefined){
                            layer.alert("固定场不能退");
                            return ;
                        }
                        var that = $(this);
                        layer.confirm('您确定要退场？', {
                        }, function(){
                            var data = util.getTokenData();
                            dojo.mixin(data, {"orderId": orderId});
                            util.post("bookCustomer/orderRefund", data).then(function (res) {
                                layer.alert(res.message);
                                if(res.code=='200'){
                                    $(that).css("background-color","")
                                        .removeAttr("bgcolor","")
                                        .removeAttr("clicked")
                                        .attr("fix","false")
                                        .text("")
                                }
                            })
                        });
                    }

                });
            })
            //退订5F
            $("#tuiding5F").bind("click",function(){
                $(".tdContent").each(function(){
                    var bgcolor = $(this).css("background-color");
                    var that = $(this);
                    if(bgcolor=='rgb(0, 128, 0)'){
                        var orderId = $(this).attr("order-id");
                        layer.confirm('您确定要退场？', {
                        }, function(){
                            var data = util.getTokenData();
                            dojo.mixin(data, {"orderId": orderId});
                            util.post("bookCustomer/orderRefund", data).then(function (res) {
                                layer.alert(res.message);
                                if(res.code=='200'){
                                    $(that).css("background-color","")
                                        .removeAttr("bgcolor","")
                                        .removeAttr("clicked")
                                        .attr("fix","false")
                                        .text("");
                                }
                            })
                        });
                    }

                });
            })

            $("#phone5").bind("change",function () {
                var phone = $(this).val();
                if(!(/^1[3|4|5|7|8][0-9]{9}$/.test(phone))){
                    return;
                }else{
                    //计算价格
                    var data = util.getTokenData();
                    dojo.mixin(data, {"phone":phone,"pid":$(".areaId").val()});
                    util.post("bookCustomer/getPrice", data).then(function (res) {
                        if(res.code==200){
                            $("#price5").val(res.data);
                        }else{
                            $("#price5").val("");
                            layer.alert(res.message);
                        }
                    });
                }
            })
        },
        initRecharge:function () {
            util.openLayer({
                area: '800px',
                shade: [0.8, '#393D49'],
                title: "充值",
                type: 1,
                content: $("#rechargeInit"),
                btn: ['充值', '关闭'],
                success: function (layero, index) {
                    $("#rechargeInitForm")[0].reset();
                },
                yes: function (layero, index) {
                    var number = $("#numberCard").val();
                    var phone = $("#phoneCard").val();
                    if(number==""&&phone==""){
                        layer.alert("请输入卡号或者手机号");
                        return ;
                    }
                    var data = util.getTokenData();
                    dojo.mixin(data, {"number": number,"phone":phone});
                    util.post("home/queryInitRecharge", data).then(function (res) {
                        if (res.code == 200) {
                            var d = res.data;
                            layer.closeAll();
                            util.openLayer({
                                area: '800px',
                                shade: [0.8, '#393D49'],
                                title: "充值",
                                type: 1,
                                content: $("#recharge2"),
                                btn: ['充值', '关闭'],
                                success: function (layero, index) {
                                    $("#rechargeForm")[0].reset();
                                    datastore.publishFormData($("#rechargeForm"), d);
                                    $("#expiredt").val(moment(d.expireDt).format("YYYY-MM-DD"));
                                },
                                yes: function (layero, index) {
                                    if ($("#rechargeForm").valid()) {
                                        $("#rechargeForm").ajaxSubmit({
                                            success: function (da) {
                                                if (da.code == 200) {
                                                    layer.closeAll();
                                                    layer.msg("充值成功");

                                                } else {
                                                    layer.msg(da.message);
                                                }
                                            }
                                        })
                                    }
                                },
                                cancel: function (index, layero) {
                                    layer.close(index);
                                }
                            });
                        }else{
                            layer.msg(res.message);
                        }
                    });
                },
                cancel: function (index, layero) {
                    layer.close(index);
                }
            });
        },
        add:function () {
            util.openLayer({
                area: '800px',
                shade: [0.8, '#393D49'],
                title: "新增",
                type: 1,
                content: $("#addWin"),
                btn: ['添加', '关闭'],
                success: function (layero, index) {
                    $("#form")[0].reset();
                    $("#status").val("");
                },
                yes: function (layero, index) {
                    if ($("#form").valid()) {
                        $("#form").ajaxSubmit({
                            success: function (d) {
                                layer.alert(d.message,function () {
                                    layer.closeAll();
                                });
                                /*if (d.code == 200) {
                                 layer.closeAll();
                                 }*/
                            }
                        })
                    }
                },
                cancel: function (index, layero) {
                    layer.close(index);
                }
            });
        },
        fixOrder:function (dom,dateDom) {
            var courtId = "";
            var startTime = "";
            var endTime ="";
            var area ="";
            var name ="";
            var pid="";
            var that = null;
            var fix = "";
            var expired ="";
            $(dom).find("tr").each(function(i,o){
                $(this).find("td").each(function(i){
                    var clicked =  $(this).attr("clicked");
                    if(clicked=='true'){
                        courtId = $(this).attr("data-id");
                        startTime= $(this).attr("data-starttime");
                        endTime= $(this).attr("data-endtime");
                        area= $(this).attr("data-area");
                        name= $(this).attr("data-name");
                        pid = $(this).attr("data-pid");
                        fix = $(this).attr("fix");
                        expired = $(this).attr("data-expired");
                        that = $(this);
                    }
                })
            });

            if(expired=="1"){
                layer.alert("该场地不能订场，时间已过");
                return;
            }
            if(courtId==""){
                layer.alert("请选择一个时间");
                return;
            }
            if(fix=="true"){
                layer.alert("该时间段已经被人预定,请选择未预定的区域!");
                return;
            }
            var time = $(dateDom).val();

            module.yudnew(pid,time,startTime,endTime,area,name,that);
        },
        yudnew:function (pid,time,startTime,endTime,area,name,that) {
            util.openLayer({
                area: '800px',
                shade: [0.8, '#393D49'],
                title: "预定",
                type: 1,
                content: $("#yuedingnew"),
                btn: ['预定', '关闭'],
                success: function (layero, index) {
                    $("#addOrder1form")[0].reset();
                    $("#addOrder2Form")[0].reset();
                    //获得选中的场地
                    $(".areaSpan").text(area+"-"+name+"号场");
                    $(".startTimeInput").val(startTime);
                    $(".endTimeInput").val(endTime);
                    $(".price").val("");
                    $(".areaId").val(pid);
                    $(".payType").val("");
                    $(".person").val("");
                    $(".phone").val("");
                },
                yes: function (layero, index) {
                    //获得选中的tab
                    var elem = $("#tabContent").find(".active");
                    var attrId=(elem.attr("id"));
                    var data = util.getTokenData();
                    if(attrId=="tab_1"){//储值卡
                        var phone = $("#phone5").val();
                        if(!(/^1[3|4|5|7|8][0-9]{9}$/.test(phone))){
                            layer.msg("手机号码有误，请重填");
                            return;
                        }
                        $("#addOrder1form").ajaxSubmit({
                            beforeSend: function(request) {
                                request.setRequestHeader("X-CSRF-TOKEN", $("#csrfToken").val());
                            },
                            success: function (d) {
                                if (d.code == 200) {
                                    layer.closeAll();
                                    $(that).attr("bgcolor","#CB5A5E");
                                    $(that).attr("fix","true");
                                    $(that).css("background-color","");
                                    $(that).css("color","white");
                                    $(that).attr("data-type","1").text("普通场");
                                    $(that).attr("order-id",d.data);
                                }
                                layer.alert(d.message);
                            }
                        });
                    }
                    if(attrId=="tab_2"){//闲散
                        var payType = $("#payType25").val();
                        var phone = $("#phone25").val();
                        if (payType==""){
                            layer.msg("请选择支付方式！");
                            return;
                        }
                        if(!(/^1[3|4|5|7|8][0-9]{9}$/.test(phone))){
                            layer.msg("手机号码有误，请重填");
                            return;
                        }
                        if(!(/^\d*(\.\d{1,2})?$/.test($("#priceDc").val()))){
                            layer.msg("请输入正确的金额");
                            return;
                        }
                        $("#addOrder2Form").ajaxSubmit({
                            beforeSend: function(request) {
                                request.setRequestHeader("X-CSRF-TOKEN", $("#csrfToken").val());
                            },
                            success: function (d) {
                                if (d.code == 200) {
                                    layer.closeAll();
                                    $(that).attr("bgcolor","#CB5A5E");
                                    $(that).attr("fix","true");
                                    $(that).css("background-color","");
                                    $(that).css("color","white");
                                    $(that).attr("data-type","1").text("普通场");
                                    $(that).attr("order-id",d.data);
                                }
                                layer.alert(d.message);
                            }
                        });

                    }
                },
                cancel: function (index, layero) {
                    layer.close(index);
                }
            });
        },
        yud:function (pid,time,startTime,endTime,area,name,that) {
            util.openLayer({
                area: '800px',
                shade: [0.8, '#393D49'],
                title: "预定",
                type: 1,
                content: $("#addWin2"),
                btn: ['预定', '关闭'],
                success: function (layero, index) {
                    //获得选中的场地
                    $("#areaSpan").text(area+"-"+name+"号场");
                    $("#startTimeInput").val(startTime);
                    $("#endTimeInput").val(endTime);
                    $("#price").val("");
                    $("#areaId").val(pid);
                    $("#payType").val("");
                    $("#person").val("");
                    $("#phone").val("")
                },
                yes: function (layero, index) {
                    var data = util.getTokenData();
                    var payType = $("#payType").val();
                    var phone = $("#phone2").val();
                    data['areaId'] = $("#areaId").val();
                    data['price']=$("#price").val();
                    data['payType']=payType;
                    data['phone']=phone;
                    data['date']=$("#date").val();
                    data['person']=$("#person").val();
                    data['startTime']=$("#startTimeInput").val();
                    data['endTime']=$("#endTimeInput").val();
                    if (payType==""){
                        layer.msg("请选择支付方式！");
                        return;
                    }
                    if(!(/^1[3|4|5|7|8][0-9]{9}$/.test(phone))){
                        layer.msg("手机号码有误，请重填");
                        return;
                    }
                    util.post("bookCustomer/addOrder", data).then(function (d) {
                        if (d.code == 200) {
                            layer.closeAll();
                            $(that).attr("bgcolor","#CB5A5E");
                            $(that).attr("fix","true");
                            $(that).css("background-color","");
                            $(that).css("color","white");
                            $(that).text("普通场");
                            $(that).attr("order-id",d.date);
                        }
                        layer.alert(d.message);
                    });

                },
                cancel: function (index, layero) {
                    layer.close(index);
                }
            });
        },
        initTable:function (area,time,th,tbody) {
            return null;
        },
        detail:function (pid) {
            if(index==0){
                index++;
                util.openLayer({
                    area: '800px',
                    shade: [0.8, '#393D49'],
                    title: "查看详细",
                    type: 1,
                    content: $("#detailWin"),
                    btn: [ '关闭'],
                    success: function (layero, index) {
                        var data = util.getTokenData();
                        dojo.mixin(data, {"pid": pid,"state":2});
                        util.post("bookCustomer/queryByPid", data).then(function (res) {
                            if(res.code==200){
                                var d = res.data;
                                var detailWinTbody = $("#detailWinTbody");
                                detailWinTbody.empty();
                                var tr="";
                                for(var i=0;i<d.length;i++){
                                    // 1 现金支付，2 刷卡支付，3转账-农商行0594，4转账-微信 5微信-中信，6支付宝
                                    var ptype= "";
                                    if(d[i].state==2){
                                        if(d[i].payType ==0){
                                            ptype = "储值卡支付";
                                        }else if(d[i].payType == 1){
                                            ptype = "现金支付";
                                        }else if(d[i].payType == 2){
                                            ptype = "刷卡支付";
                                        }else if(d[i].payType == 3){
                                            ptype = "支付宝";
                                        }else if(d[i].payType == 4){
                                            ptype = "糯米网";
                                        }else if(d[i].payType == 11){
                                            ptype = "微信支付";
                                        }
                                    }else{
                                        ptype = "待支付";
                                    }
                                    tr+="<tr><td>"+d[i].id+"</td>" +
                                        "<td>"+d[i].area+"-"+d[i].name+" </td>" +
                                        "<td>"+moment(d[i].startTime).format("HH:mm")+" </td>" +
                                        "<td>"+moment(d[i].endTime).format("HH:mm")+" </td>" +
                                        "<td>"+ptype+" </td>" +
                                        "<td>"+d[i].person+" </td>" +
                                        "<td>"+d[i].phone+" </td>" +
                                        "<td>"+d[i].memberNum+" </td>" +
                                        "<td>"+moment(d[i].createdDt).format("YYYY-MM-DD")+" </td>" +
                                        "<td>"+d[i].comment+" </td>" +
                                        "</tr>";
                                }
                                detailWinTbody.append(tr);
                            }
                        });
                    },
                    yes: function (layero, i) {
                        layer.closeAll();
                        index = 0;
                    },
                    cancel: function (i, layero) {
                        layer.close(i);
                        index = 0;
                    }

                });
            }
        },
        validateForm: function () {
            var validate = $('#rechargeForm').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                rules: {
                    rechargePrice:{
                        required: true
                    },
                    payWay:{
                        required: true
                    }
                },
                messages: {
                    rechargePrice:{
                        required: "请选择充值金额"
                    },
                    payWay:{
                        required: "请选择支付方式"
                    }
                },
                highlight: function (element) { // hightlight error inputs
                    $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
                },
                unhighlight: function (element) { // revert the change done by hightlight
                    $(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
                },
                success: function (label) {
                    label.closest('.form-group').removeClass('has-error');
                },
                errorPlacement: function (error, element) {
                    if (element.parent(".input-group").size() > 0) {
                        error.insertAfter(element.parent(".input-group"));
                    } else if (element.attr("data-error-container")) {
                        error.appendTo(element.attr("data-error-container"));
                    } else if (element.parents('.radio-list').size() > 0) {
                        error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                    } else if (element.parents('.radio-inline').size() > 0) {
                        error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                    } else if (element.parents('.checkbox-list').size() > 0) {
                        error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                    } else if (element.parents('.checkbox-inline').size() > 0) {
                        error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                    } else {
                        error.insertAfter(element); // for other inputs, just perform default behavior
                    }
                }
            });
            return validate;
        }
    }
    return module;
});